import React, { useState, useEffect } from "react";
import { useCookies } from "react-cookie";
import Box from "./Box";
import Text from "./Text";
import { Star } from "@styled-icons/boxicons-solid/Star";

// localStorage键名常量
export const MAGIC_POINTS_KEY = "user_magic_points";
export const MAGIC_HISTORY_KEY = "user_magic_history";
export const DOWNLOAD_MAGIC_CONVERSION_KEY = "download_magic_conversion";

// 检查是否在浏览器环境
const isBrowser = typeof window !== 'undefined';

// 增加魔力值并保存到localStorage
export const addMagicPoints = (points, reason) => {
  if (!isBrowser) return 0;
  
  // 读取当前魔力值
  const currentPoints = getMagicPoints();
  
  // 增加魔力值
  const newPoints = currentPoints + points;
  
  // 保存新的魔力值
  localStorage.setItem(MAGIC_POINTS_KEY, newPoints.toString());
  
  // 记录历史
  const timestamp = new Date().toISOString();
  const history = getMagicHistory();
  const newHistory = [
    {
      id: Date.now(),
      type: points >= 0 ? "gain" : "cost",
      amount: Math.abs(points),
      reason: reason || (points >= 0 ? "获得魔力值" : "消耗魔力值"),
      date: new Date().toLocaleString(),
      timestamp
    },
    ...history
  ];
  
  // 最多保存50条历史记录
  const trimmedHistory = newHistory.slice(0, 50);
  localStorage.setItem(MAGIC_HISTORY_KEY, JSON.stringify(trimmedHistory));
  
  return newPoints;
};

// 获取当前魔力值
export const getMagicPoints = () => {
  if (!isBrowser) return 0;
  
  const points = localStorage.getItem(MAGIC_POINTS_KEY);
  return points ? parseInt(points, 10) : 0;
};

// 获取魔力值历史
export const getMagicHistory = () => {
  if (!isBrowser) return [];
  
  const history = localStorage.getItem(MAGIC_HISTORY_KEY);
  return history ? JSON.parse(history) : [];
};

// 将下载量转换为魔力值（乘以10）
export const convertDownloadToMagic = (downloadedBytes) => {
  // 将字节转换为GB
  const downloadedGB = downloadedBytes / (1024 * 1024 * 1024);
  
  // 计算魔力值（下载量GB乘以10）
  const magicPoints = Math.floor(downloadedGB * 10);
  
  // 检查是否已经进行过转换
  const hasConverted = isBrowser ? localStorage.getItem(DOWNLOAD_MAGIC_CONVERSION_KEY) === "true" : false;
  
  if (isBrowser && !hasConverted && magicPoints > 0) {
    // 添加魔力值
    addMagicPoints(magicPoints, "下载量转换为魔力值");
    
    // 标记已转换，避免重复转换
    localStorage.setItem(DOWNLOAD_MAGIC_CONVERSION_KEY, "true");
    
    return {
      magicPoints,
      isNewConversion: true
    };
  }
  
  return {
    magicPoints,
    isNewConversion: false
  };
};

// 检查今天是否已签到
export const hasCheckedInToday = () => {
  if (!isBrowser) return false;
  
  const today = new Date().toLocaleDateString();
  const lastCheckIn = localStorage.getItem('last_check_in_date');
  return lastCheckIn === today;
};

// 获取当月签到记录
export const getMonthlyCheckins = (year, month) => {
  if (!isBrowser) return [];
  
  if (!year || !month) {
    const today = new Date();
    year = today.getFullYear();
    month = today.getMonth() + 1;
  }
  
  const recordKey = `check_in_record_${year}_${month}`;
  const record = localStorage.getItem(recordKey);
  return record ? JSON.parse(record) : [];
};

// 检查是否应该显示签到弹窗
export const shouldShowCheckInPrompt = () => {
  if (!isBrowser) return false;
  
  // 如果今天已经签到过了，不显示
  if (hasCheckedInToday()) {
    return false;
  }
  
  // 获取上次登录的日期
  const lastLogin = localStorage.getItem('last_login_date');
  const today = new Date().toLocaleDateString();
  
  // 更新最后登录日期
  localStorage.setItem('last_login_date', today);
  
  // 如果今天是第一次登录且未签到，显示弹窗
  return lastLogin !== today;
};

// 获取当月总天数
export const getLastDayOfMonth = (date) => {
  return new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
};

// 检查当月全勤状态
export const getMonthlyCheckinStatus = () => {
  const today = new Date();
  const year = today.getFullYear();
  const month = today.getMonth() + 1;
  
  const daysInMonth = getLastDayOfMonth(today);
  const checkins = getMonthlyCheckins(year, month);
  
  return {
    total: daysInMonth,
    completed: checkins.length,
    remaining: daysInMonth - checkins.length,
    isComplete: checkins.length >= daysInMonth,
    bonusClaimed: localStorage.getItem(`monthly_bonus_${year}_${month}`) === 'claimed'
  };
};

const UserMagic = ({ onMagicUpdate, refreshTrigger }) => {
  const [magic, setMagic] = useState(0);
  const [loading, setLoading] = useState(true);
  const [cookies] = useCookies();
  const { username } = cookies;
  const [checkinStatus, setCheckinStatus] = useState({
    total: 0,
    completed: 0,
    remaining: 0
  });

  const fetchMagic = () => {
    if (!username) {
      setLoading(false);
      return;
    }

    try {
      setLoading(true);
      
      // 从localStorage获取魔力值
      const currentMagic = getMagicPoints();
      setMagic(currentMagic);
      
      // 获取签到状态
      setCheckinStatus(getMonthlyCheckinStatus());
      
      if (onMagicUpdate) {
        onMagicUpdate(currentMagic);
      }
    } catch (error) {
      console.error("获取魔力失败:", error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchMagic();
  }, [username, refreshTrigger]);

  if (loading) {
    return (
      <Box p={3} bg="sidebar" borderRadius={1}>
        <Text>加载魔力值...</Text>
      </Box>
    );
  }

  return (
    <Box p={3} bg="sidebar" borderRadius={1}>
      <Box display="flex" alignItems="center">
        <Star size={24} color="#FFD700" />
        <Text ml={2} fontWeight="bold" fontSize={2}>
          魔力值
        </Text>
      </Box>
      <Box mt={2}>
        <Text fontSize={3} fontWeight="bold" color="primary">
          {magic}
        </Text>
        <Text fontSize={1} color="grey" mt={1}>
          完成任务和评分可获得魔力值
        </Text>
      </Box>
      
      <Box mt={3} pt={3} borderTop="1px solid" borderColor="border">
        <Text fontSize={1} fontWeight="bold" mb={2}>
          本月签到: {checkinStatus.completed}/{checkinStatus.total}
        </Text>
        <Box 
          width="100%" 
          height="4px" 
          bg="#eee" 
          borderRadius="2px" 
          overflow="hidden"
        >
          <Box 
            width={`${(checkinStatus.completed / checkinStatus.total) * 100}%`} 
            height="100%" 
            bg="primary"
          />
        </Box>
        <Text fontSize={0} color="grey" mt={1}>
          {hasCheckedInToday() ? "今日已签到" : "今日未签到"}
          {checkinStatus.isComplete && !checkinStatus.bonusClaimed && 
            <Text as="span" color="success"> • 可领取月度奖励</Text>
          }
        </Text>
      </Box>
    </Box>
  );
};

export default UserMagic;
